package com.jin.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jin.VO.ResultVO;

import com.jin.dto.OrderDTO;
import com.jin.entity.OrderMaster;
import com.jin.enums.ResultEnum;
import com.jin.exception.SellException;
import com.jin.form.OrderForm;
import com.jin.service.OrderService;
import com.jin.utils.ResultVOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author JJLiu
 * @create 2021-07-20 16:26
 **/
@RestController
@RequestMapping("/buyer/order")
@Slf4j
public class BuyerOrderController {

    @Autowired
    private OrderService orderService;

    //创建订单
    @PostMapping("/create")
    public ResultVO<Map<String,String>> create(@Valid @RequestBody OrderForm orderForm,
                                                BindingResult bindingResult) {
        if(bindingResult.hasErrors()) {
            log.error("【表单异常】参数不正确, orderForm={}",orderForm);
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(),
                    Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
//        OrderDTO orderDTO = OrderFormToOrderDTOConverter.convert(orderForm);
        if(CollectionUtils.isEmpty(orderForm.getItems())) {
            log.error("【创建订单】购物车不能为空 ");
            throw new SellException(ResultEnum.CART_EMPTY);
        }
        OrderForm createResult = orderService.create(orderForm);
        
        Map<String,String> map = new HashMap<>();
        map.put("orderId",createResult.getItems().get(0).getOrderId());

        return ResultVOUtils.success(map);
    }

    //订单列表
    @GetMapping("/list")
    public ResultVO<List<OrderDTO>> list(@RequestParam("openid") String openid,
                                         @RequestParam(value = "page", defaultValue = "0") Integer page,
                                         @RequestParam(value = "size", defaultValue = "10") Integer size) {
        if (StringUtils.isBlank(openid)) {
            log.error("【查询订单列表】openid为空");
            throw new SellException(ResultEnum.PARAM_ERROR);
        }

        Page<OrderMaster> iPage = new Page<>(page,size);
        List<OrderDTO> orderDTOList = orderService.findList(openid, iPage);

        return ResultVOUtils.success(orderDTOList);
    }
}
